<?php
session_start();
include("../utility/connection.php");
include("../model/mPaper.php");
include("../model/mFile.php");
if (($_FILES['txtFile']['size'] > 0) && ($_FILES['txtFile']['size'] < 8000000)) {
    // SIMPAN INFO PAPER-NYA TERLEBIH DAHULU
    $Title = trim(mysql_real_escape_string($_POST["txtTitle"]));
    $fileInfo = trim(mysql_real_escape_string($_POST["txtUraian"]));
    $SeminarId = $_SESSION['topikId'];
    $UserId = $_SESSION['userId'];
    
    $result = fnInsertPaper($UserId,$SeminarId,$Title,$fileInfo);
    if ($result) {
        // AMBIL PAPER ID-NYA
        $result1 = fnGetPaperId($UserId,$SeminarId,$Title);
        $paperResult = mysql_fetch_array($result1);
        $PaperId = $paperResult[0];
        // UPLOAD FILE-NYA
        fnUploadFile($PaperId,$SeminarId,$UserId);
        
    } else {
        echo 'Gagal Upload File. Coba lagi!';
    }
} else {
    unset($_SESSION['uploadSukses']);
    $_SESSION['uploadMessage'] = 'Upload File '.$fileName.' Tidak Berhasil. Ukuran File Terlalu Besar.';
    header("location: ../ui/user/uploadFile.php?size=$fileSize");
}

function fnUploadFile($PaperId) {
    // SIMPAN FILE NYA
    $fileName = $_FILES['txtFile']['name'];
    $tmpName = $_FILES['txtFile']['tmp_name'];
    $fileSize = $_FILES['txtFile']['size'];
    $fileType = $_FILES['txtFile']['type'];
    
    $fp = fopen($tmpName, 'r');
    $content = fread($fp, filesize($tmpName));
    $content = addslashes($content);
    fclose($fp);

    if (!get_magic_quotes_gpc()) {
        $fileName = addslashes($fileName);
    }
    
    //$PaperId = '1';

    $result = fnInsertFile($PaperId,$fileName,$content,$fileSize,$fileType);

    if ($result) {
        $_SESSION['uploadSukses'] = '1';
        $_SESSION['uploadMessage'] = 'Upload File '.$fileName.' Berhasil';
        header("location: ../ui/user/uploadFile.php?size=$fileSize");
//        echo 'Berhasil Upload File. Tutup window ini!';
//        echo 'PaperId: '.$PaperId;
    } else {
        unset($_SESSION['uploadSukses']);
        $_SESSION['uploadMessage'] = 'Upload File '.$fileName.' Tidak Berhasil';
        header("location: ../ui/user/uploadFile.php?size=$fileSize");
//        echo 'Gagal Upload File. Coba lagi!';
//        echo 'PaperId: '.$PaperId;
    }
}
?>
